<!-- 储存空间 -->
<template>
  <div class="content">
    <div class="infoBox">
      <PieChart
        style="width: 35%"
        v-if="PieCharModel"
        ref="PieChartRef"
        :data="StorageData"
      />
      <TrendChart style="width: 50%" ref="TrendChartRef" :data="ChartData" />
      <!-- <RadarChart /> -->
    </div>

    <!-- <Progress :totalSpace="100100" :usedSpace="50100" /> -->

    <div class="storageManagement">
      <div class="storageManagement-title">
        <h3>存储管理</h3>
        <a-button type="primary" @click="addStora">新增云盘</a-button>
      </div>
      <TableTurn
        :tableData="getTableData"
        :args="args"
        ref="tableRef"
        :isShowPagination="false"
      >
        <a-table-column :width="60" title="序号" fixed="left">
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column :width="150" dataIndex="diskName" title="云盘名称	">
        </a-table-column>
        <a-table-column :width="150" title="已使用空间	"
          ><template #cell="{ record }">{{
            bytesToSize(record.usedDiskSpace)
          }}</template>
        </a-table-column>
        <a-table-column
          :width="150"
          dataIndex="type"
          title="预分配容量（专享容量）	"
          ><template #cell="{ record }"
            ><div v-if="!record.diskSpace && !record.isEdit">
              <span>共享剩余{{ bToGb(remainingCapacity) }}GB</span
              ><a-button type="text" @click="record.isEdit = true"
                >分配</a-button
              >
            </div>
            <div v-if="record.isEdit">
              <a-input-number
                :style="{ width: '100px' }"
                :min="0"
                :precision="0"
                @change="editStorageSpace($event, record)"
                @blur="record.isEdit = false"
              />GB
            </div>
            <div v-if="record.diskSpace && !record.isEdit">
              <span>{{ bToGb(record.diskSpace) }}GB</span
              ><a-button type="text" @click="record.isEdit = true"
                >修改</a-button
              >
            </div></template
          >
        </a-table-column>
        <a-table-column :width="200" dataIndex="remark" title="描述	">
        </a-table-column>

        <a-table-column :width="150" dataIndex="describe" title="最后活跃时间	"
          ><template #cell="{ record }">{{
            dayjs(record.updatedAt).format('YYYY-MM-DD')
          }}</template>
        </a-table-column>
        <a-table-column :width="200" title="操作	">
          <template #cell="{ record }">
            <!-- <a-button type="text""
              >查看详情</a-button
            > -->

            <!-- <a-tooltip content="查看详情">
              <a-popconfirm content="确认删除?" type="error" @ok="del(record)">
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm> </a-tooltip
          > -->
            <a-tooltip content="查看详情">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{ cursor: 'pointer', marginRight: '10px' }"
                @click="goManagementPage(record)"
              />
            </a-tooltip>
          </template>
        </a-table-column>
      </TableTurn>
    </div>
  </div>
  <!-- </ContentCard> -->
  <DocumentModel
    v-model:visible="modalVisible"
    :data="data"
    @addDocumentEmit="addDocumentEmit"
  ></DocumentModel>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import {
  GetDocumentCenterListAll,
  PutStorageDisk,
  getClientDisk,
  getClientStorageSpace,
  putClientStorageSpace,
  postClientDisk
} from '@/apis/document/documentCenter/index';
import PieChart from './components/PieChart.vue';
import TrendChart from './components/TrendChart.vue';
import DocumentModel from './components/DocumentModel.vue';
import dayjs from 'dayjs';
import RadarChart from './components/RadarChart.vue';

// let PieChart = defineAsyncComponent(() => import('./components/PieChart.vue'));
const router = useRouter();
const PieCharModel = ref(false);
const PieChartRef = ref();
const data = ref({
  diskName: '',
  diskSpace: undefined,
  remark: '',
  type: undefined
});
const ChartData = ref([]);
const tableRef = ref();
const modalVisible = ref(false);
const userId = Number(localStorage.getItem('userId'));
const StorageData = ref({});
const remainingCapacity = ref();
const clientDisk = ref();
// const StorageSpace
const getTableData = async (page: any) => {
  try {
    const res = await getClientDisk();
    clientDisk.value = res;
    StorageData.value = await getClientStorageSpace();
    PieCharModel.value = true;
    return Promise.resolve(res);
  } catch (err: unknown) {
    console.log(err);
  }
};

function bytesToSize(bytes: any) {
  if (bytes === 0) return '0 B';
  var k = 1024, // or 1024
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

const editStorageSpace = async (diskSpace: any, record: any) => {
  try {
    if (!diskSpace) record.isEdit = false;
    diskSpace = diskSpace * 1024 * 1024 * 1024;
    await putClientStorageSpace({ id: record.id, diskSpace });
    tableRef.value.loadData();
  } catch (err: unknown) {
    console.log(err);
  }
};

// B to GB
function bToGb(b: number): number {
  return b / (1024 * 1024 * 1024);
}

const addStora = () => {
  modalVisible.value = true;
};

const goManagementPage = (record: any) => {
  console.log(record);
  if (record.diskName === '个人盘') {
    router.push({ name: 'StorageManagement' });
  }
};

watchEffect(() => {
  if (clientDisk.value) {
    let msg = 0;
    clientDisk.value.forEach((element: any) => {
      msg += element.diskSpace;
    });
    remainingCapacity.value = StorageData.value.storageSpace - msg;
  }
});

const addDocumentEmit = async (res: any) => {
  await postClientDisk({ ...res });
  tableRef.value.loadData();
};
</script>

<style lang="less" scoped>
.content {
  margin: 20px;
  margin-right: 60px;
  background-color: #f5f7fb;
  // width: 100%;
  // height: 100%;
  .infoBox {
    padding: 20px;
    border-radius: 8px;
    width: 100%;
    height: 300px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
  }
  .useInfoBox {
    margin-top: 20px;
    width: 100%;
    height: 300px;
    display: flex;
    justify-content: space-between;
    .usageBox {
      background-color: #fff;
      width: 50%;
      height: 300px;
      border-radius: 8px;
      // border: 1px solid red;
    }
  }

  .storageManagement {
    padding: 20px;
    margin-top: 20px;
    width: 100%;
    background-color: #fff;
    &-title {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
